package com.yanqu.road.server.gameplayer.module.activity.strongholdwar;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UnionActivityConditionData;
import com.yanqu.road.entity.activity.stronghold.StrongholdPatronsData;
import com.yanqu.road.entity.activity.stronghold.StrongholdWarUserData;
import com.yanqu.road.entity.activity.stronghold.StrongholdWildReport;
import com.yanqu.road.entity.activity.stronghold.config.StrongholdTradeConfig;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eSkillType;
import com.yanqu.road.entity.log.stronghold.LogStrongholdPower;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.logic.bussiness.player.activity.UserStrongholdBusiness;
import com.yanqu.road.logic.helper.CalcPowerResult;
import com.yanqu.road.logic.helper.PowerHelper;
import com.yanqu.road.pb.activity.StrongholdWarProto;
import com.yanqu.road.pb.rank.UnionActivityRankProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.vehicle.VehicleModule;
import com.yanqu.road.server.manger.activity.curio.CurioMgr;
import com.yanqu.road.server.manger.activity.strongholdwar.StrongholdActivityMgr;
import com.yanqu.road.server.manger.activity.strongholdwar.StrongholdActivityRankMgr;
import com.yanqu.road.server.manger.activity.strongholdwar.StrongholdWarMgr;
import com.yanqu.road.server.manger.cross.CrossDataMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class StrongholdModule extends GeneralModule {

    private Map<Integer, StrongholdWarUserData> userDataMap;

    private Map<Integer, Map<Integer, StrongholdPatronsData>> patronsMap;

    private Map<Integer, List<StrongholdWildReport>> wildReportMap;

    public StrongholdModule(GamePlayer player) {
        super(player);
    }

    /**
     * 根据活动Id 获取据点战玩家个人数据
     *
     * @param activityId 活动id
     */
    public StrongholdWarUserData getStrongholdWarData(int activityId) {
        StrongholdWarUserData data = userDataMap.get(activityId);
        if (data == null) {
            data = new StrongholdWarUserData();
            data.setActivityId(activityId);
            data.setUserId(getUserId());
            data.setLastRestoreTime(System.currentTimeMillis() / 1000);
            data.setPower(StrongholdActivityMgr.getWildInitPower());
            data.setInsertOption();
            userDataMap.put(activityId, data);
        }
        return data;
    }

    /**
     * 重新计算当前体力
     *
     * @param data
     */
    public void calcPower(StrongholdWarUserData data) {
        if (data != null) {
            CalcPowerResult result = PowerHelper.calcPower(data.getLastRestoreTime(), StrongholdActivityMgr.getWildPowerRecoverTime(), 1, StrongholdActivityMgr.getWildMaxPower(), data.getPower());
            data.setLastRestoreTime(result.getLastRecoverTime());
            data.setPower(result.getCurPower());
        }
    }

    @Override
    public boolean loadData() {
        patronsMap = new ConcurrentHashMap<>();
        wildReportMap = new ConcurrentHashMap<>();
        userDataMap = new ConcurrentHashMap<>();
        ActivityInfo activityInfo = StrongholdActivityMgr.getActivityInfo();
        if (activityInfo != null) {
            int activityId = activityInfo.getActivityId();
            userDataMap = UserStrongholdBusiness.getStrongholdWarUserData(getUserId());
            Map<Integer, StrongholdPatronsData> dataMap = UserStrongholdBusiness.getStrongholdPatronsMap(activityId, getUserId());
            patronsMap.put(activityId, dataMap);
            StrongholdWarUserData userData = getStrongholdWarData(activityId);
            calcPower(userData);
            wildReportMap = UserStrongholdBusiness.getWildReport(getUserId(), activityId);
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        ActivityInfo activityInfo = StrongholdActivityMgr.getOpenActivityInfo();
        resetBattlePatrons();
       /* if (activityInfo != null) {
            StrongholdWarUserData warUserData = getStrongholdWarData(activityInfo.getActivityId());
            calcPower(warUserData);
        }*/
        for (StrongholdWarUserData data : new ArrayList<>(userDataMap.values())) {
            if (data.isInsertOption()) {
                UserStrongholdBusiness.addStrongholdUserData(data);
            } else if (data.isUpdateOption()) {
                UserStrongholdBusiness.updateStrongholdUserData(data);
            }
        }
        for (Map<Integer, StrongholdPatronsData> dataMap : patronsMap.values()) {
            for (StrongholdPatronsData data : dataMap.values()) {
                if (data.isInsertOption()) {
                    UserStrongholdBusiness.addStrongholdPatrons(data);
                } else if (data.isUpdateOption()) {
                    UserStrongholdBusiness.updateStrongholdPatrons(data);
                }
            }
        }
        for (List<StrongholdWildReport> reportList : new ArrayList<>(wildReportMap.values())) {
            List<StrongholdWildReport> saveReportList;
            synchronized (reportList) {
                saveReportList = new ArrayList<>(reportList);
            }
            for (StrongholdWildReport report : saveReportList) {
                if (report.isInsertOption()) {
                    UserStrongholdBusiness.addWildReport(report);
                } else if (report.isUpdateOption()) {
                    UserStrongholdBusiness.updateWildReport(report);
                }
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        resetBattlePatrons();
        syncUserData();
        noticeWildReportRedPoint();
        ActivityInfo activityInfo = StrongholdActivityMgr.getActivityInfo();
        if (activityInfo != null) {
            if (StrongholdActivityMgr.isEliminateTime()) {
                StrongholdWarProto.CrossStrongholdEliminateUnionStatusReqMsg.Builder req = StrongholdWarProto.CrossStrongholdEliminateUnionStatusReqMsg.newBuilder();
                req.setUnionId(player.getUserInfo().getUnionUid());
                req.setActivityId(activityInfo.getActivityId());
                player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_STRONGHOLD_ELIMINATE_UNION_STATUS, req, req.getActivityId());
            }
        }
    }

    @Override
    public void loginSendMsg() {

    }

    public void syncUserData() {
        ActivityInfo activityInfo = StrongholdActivityMgr.getActivityInfo();
        if (activityInfo != null) {
            int activityId = activityInfo.getActivityId();
            StrongholdWarUserData data = getStrongholdWarData(activityId);
            Map<Integer, StrongholdPatronsData> dataMap = patronsMap.get(activityId);
            StrongholdWarProto.StrongholdWildDataMsg.Builder msg = StrongholdWarProto.StrongholdWildDataMsg.newBuilder();
            msg.setPower(data.getPower());
            msg.setLastRestoreTime(data.getLastRestoreTime());
            msg.setGuide(data.getGuide());

            if (dataMap != null) {
                for (StrongholdPatronsData patronsWarData : dataMap.values()) {
                    StrongholdWarProto.StrongholdWarPatronsDataTempMsg.Builder builder = StrongholdWarProto.StrongholdWarPatronsDataTempMsg.newBuilder();
                    builder.setPatronsId(patronsWarData.getPatronsId());
                    builder.setFreeTimes(patronsWarData.getFreeTimes());
                    builder.setBuyTimes(patronsWarData.getBuyTimes());
                    msg.addPatrons(builder);
                }
            }
            msg.addAllEliminateDefendPatronsId(StrongholdWarMgr.getEliminateDefendPatrons(activityId, player.getUserInfo().getUnionUid(), player.getUserId()));
            int myTradeAddress = StrongholdWarMgr.getMyTradeAddress(activityId, player.getUserId());
            msg.setAddress(myTradeAddress);
            msg.setHasQualification(StrongholdWarMgr.hasQualification(activityId, player.getUserInfo().getUnionUid()));
            msg.setCanAddress(0);
            if (myTradeAddress == 0) {
                if (!StrongholdActivityMgr.isRewardTime()) {
                    msg.setCanAddress(0);
                } else {
                    UnionActivityConditionData unionActivityConditionData = StrongholdActivityRankMgr.getUnionActivityConditionData(activityId, StrongholdActivityMgr.CONDITION_TYPE_ELIMINATE_UNION, player.getUserId());
                    if (unionActivityConditionData != null) {
                        int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, player.getUserId());
                        UnionActivityRankProto.UnionActivityRankListMsg rankList = CrossDataMgr.getCrossActivityUnionConditionTypeRankList(activityId, groupId, StrongholdActivityMgr.CONDITION_TYPE_ELIMINATE_UNION);
                        if (rankList != null && rankList.getRankListCount() > 0) {
                            int myrank = 0;
                            int rank = 0;
                            for (UnionActivityRankProto.UnionActivityRankTempMsg tempMsg : rankList.getRankListList()) {
                                rank++;
                                if (tempMsg.getUnionUid().equals(unionActivityConditionData.getUnionUid())) {
                                    myrank = rank;
                                    break;
                                }
                            }
                            Map<Integer, StrongholdTradeConfig> tradeConfigMap = StrongholdActivityMgr.getTradeConfigMap();
                            for (StrongholdTradeConfig config : tradeConfigMap.values()) {
                                String[] split = config.getRankRange().split("\\|");
                                int beginRank = Integer.parseInt(split[0]);
                                int endRank = Integer.parseInt(split[1]);
                                if (myrank >= beginRank && myrank <= endRank) {
                                    msg.setCanAddress(config.getId());
                                }
                            }
                        }
                    }
                }
            }
            player.sendPacket(ClientProtocol.U_STRONGHOLD_WAR_USER_DATA, msg);
        }
    }


    /**
     * 增加门客派遣次数
     *
     * @param patronsId
     */
    public void addBattlePatrons(int patronsId) {
        if (patronsId <= 0) {
            return;
        }
        ActivityInfo activityInfo = StrongholdActivityMgr.getActivityInfo();
        if (activityInfo != null) {
            int activityId = activityInfo.getActivityId();
            Map<Integer, StrongholdPatronsData> dataMap = patronsMap.get(activityId);
            if (dataMap == null) {
                dataMap = new ConcurrentHashMap<>();
                patronsMap.put(activityId, dataMap);
            }
            StrongholdPatronsData patronsData = dataMap.get(patronsId);
            if (patronsData == null) {
                patronsData = new StrongholdPatronsData();
                patronsData.setActivityId(activityId);
                patronsData.setUserId(getUserId());
                patronsData.setPatronsId(patronsId);
                patronsData.setInsertOption();
                dataMap.put(patronsId, patronsData);
            }
            int freeTimes = StrongholdActivityMgr.getPatronsFreeTimes(player, patronsId);
            if (patronsData.getFreeTimes() >= freeTimes) {
                patronsData.setBuyTimes(patronsData.getBuyTimes() + 1);
            } else {
                patronsData.setFreeTimes(patronsData.getFreeTimes() + 1);
            }
            syncUserData();
            //珍兽绑定 鱼类绑定
            player.getModule(VehicleModule.class).bindPatrons(patronsId, activityId);
        }
    }

    public void resetBattlePatrons() {
        ActivityInfo activityInfo = StrongholdActivityMgr.getActivityInfo();
        if (activityInfo != null) {
            int timeId = StrongholdActivityMgr.getTimeId();
            if (timeId != 0) {
                int activityId = activityInfo.getActivityId();
                StrongholdWarUserData userData = getStrongholdWarData(activityId);
                if (userData.getResetPatronsTimeId() < timeId) {
                    userData.setResetPatronsTimeId(timeId);
                    Map<Integer, StrongholdPatronsData> dataMap = patronsMap.get(activityId);
                    if (dataMap != null) {
                        for (StrongholdPatronsData data : dataMap.values()) {
                            data.setFreeTimes(0);
                            data.setBuyTimes(0);
                        }
                    }
                    syncUserData();
                }
            }
        }
    }

    public void receiveWildReport(StrongholdWildReport report) {
        List<StrongholdWildReport> reportList;
        synchronized (wildReportMap) {
            reportList = wildReportMap.computeIfAbsent(report.getActivityId(), k -> new ArrayList<>());
            reportList.add(0, report);
        }
        noticeWildReportRedPoint();
    }

    /**
     * 通知红点
     */
    private void noticeWildReportRedPoint() {
        ActivityInfo activityInfo = StrongholdActivityMgr.getOpenActivityInfo();
        if (activityInfo == null) {
            return;
        }
        int activityId = activityInfo.getActivityId();
        List<StrongholdWildReport> reportList = wildReportMap.get(activityId);

        boolean hasUnReadReport = false;
        if (reportList != null) {
            for (StrongholdWildReport report : reportList) {
                if (!report.isRead()) {
                    hasUnReadReport = true;
                    break;
                }
            }
        }
        StrongholdWarProto.WildReportRedPointMsg.Builder msg = StrongholdWarProto.WildReportRedPointMsg.newBuilder();
        msg.setHasRed(hasUnReadReport);
        player.sendPacket(ClientProtocol.U_STRONGHOLD_WILD_REPORT_RED_POINT, msg);
    }

    public List<StrongholdWildReport> getWildReportList() {
        ActivityInfo activityInfo = StrongholdActivityMgr.getActivityInfo();
        if (activityInfo == null) {
            return new ArrayList<>();
        }
        List<StrongholdWildReport> reportList = wildReportMap.get(activityInfo.getActivityId());
        if (reportList == null) {
            return new ArrayList<>();
        }
        for (StrongholdWildReport report : reportList) {
            report.setRead(true);
        }
        noticeWildReportRedPoint();
        return new ArrayList<>(reportList);
    }

    public boolean containDispatchPatrons(int activityId, int patronsId) {
        Map<Integer, StrongholdPatronsData> dataMap = patronsMap.get(activityId);
        if (dataMap == null) {
            return false;
        }
        return dataMap.containsKey(patronsId);
    }

    /**
     * 增加积分 都走这边吧
     *
     * @param addPoints
     */
    public void addRewardPoints(int addPoints) {
        ActivityInfo openActivityInfo = StrongholdActivityMgr.getOpenActivityInfo();
        if (openActivityInfo != null) {
            player.notifyListener(eGamePlayerEventType.StrongholdWildScoreRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, BigInteger.valueOf(addPoints), player.getUserInfo().getUnionUid()));
        }
    }

    public void setEventConsume(int activityId, String consume) {
        StrongholdWarUserData userData = getStrongholdWarData(activityId);
        userData.setEvent(consume);
    }

    public void reducePower(int reducePower, int way) {
        ActivityInfo activityInfo = StrongholdActivityMgr.getActivityInfo();
        if (activityInfo != null) {
            StrongholdWarUserData strongholdWarData = getStrongholdWarData(activityInfo.getActivityId());
            calcPower(strongholdWarData);
            strongholdWarData.setPower(strongholdWarData.getPower() - reducePower);
            syncUserData();
            AutoLogMgr.add(new LogStrongholdPower(activityInfo.getActivityId(), getUserId(), reducePower, way));
        }

    }

    public void addDamage(BigInteger damage) {
        ActivityInfo openActivityInfo = StrongholdActivityMgr.getOpenActivityInfo();
        if (openActivityInfo != null) {
            player.notifyListener(eGamePlayerEventType.StrongholdEliminateRank.getValue(), new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, damage, player.getUserInfo().getUnionUid()));
        }
    }

    public Map<Integer, StrongholdPatronsData> getDispatchMap(int activityId) {
        return patronsMap.get(activityId);
    }

    public void addPower(int activityId, int recoverNum) {
        StrongholdWarUserData userData = getStrongholdWarData(activityId);
        calcPower(userData);
        userData.setPower(userData.getPower() + recoverNum);
        syncUserData();
    }

    public void initSystem() {
        ActivityInfo activityInfo = StrongholdActivityMgr.getOpenActivityInfo();
        if (activityInfo != null) {
            syncUserData();
        }
    }

    public void patronsAbilityChange(List<UserPatrons> patronsList) {
        try {
            ActivityInfo activityInfo = StrongholdActivityMgr.getOpenActivityInfo();
            if (activityInfo == null) {
                return;
            }
            //是否是派遣时间
            if (!StrongholdActivityMgr.isDispatchEliminatePatronsTime()) {
                return;
            }
            int activityId = activityInfo.getActivityId();
            String unionUid = player.getUserInfo().getUnionUid();
            if (StrongholdWarMgr.hasQualification(player)) {
                long otherAddition = CurioMgr.getSkillAdditionBySkillType(eSkillType.StrongholdWarPatronsSkill.getValue(), player, 0);
                StrongholdWarMgr.autoDispatchPatrons(activityId, player.getUserId(), unionUid, otherAddition);
            }
          /*  List<Integer> list = StrongholdWarMgr.getEliminateDefendPatrons(activityId, unionUid, player.getUserId());
            if (list == null || list.isEmpty()) {
                return;
            }
            boolean reDispatch = false;
            for (UserPatrons patrons : patronsList) {
                if (list.contains(patrons.getPatronsId())) {
                    reDispatch = true;
                }
            }
            if (!reDispatch) {
                return;
            }
            List<UserPatrons> clonePatronsList = new ArrayList<>();
            for (Integer patronsId : list) {
                UserPatrons patrons = player.getModule(PatronsModule.class).getUserPatrons(patronsId);
                if (patrons != null) {
                    clonePatronsList.add(patrons.cloneUserPatrons());
                }
            }

            StrongholdWarMgr.dispatchDefendPatrons(activityId, unionUid, player.getUserId(), clonePatronsList, player.getModule(PatronsModule.class).getUserPatronsMap());*/

        } catch (Exception e) {

        }
    }

    public StrongholdPatronsData getChallengePatronsData(int activityId, int patronsId) {
        Map<Integer, StrongholdPatronsData> dataMap = patronsMap.get(activityId);
        if (dataMap == null) {
            return null;
        }
        return dataMap.get(patronsId);
    }

    public void finishGuide(String guide) {
        ActivityInfo activityInfo = StrongholdActivityMgr.getOpenActivityInfo();
        if (activityInfo != null) {
            StrongholdWarUserData data = getStrongholdWarData(activityInfo.getActivityId());
            data.setGuide(guide);
            syncUserData();
        }
    }
}
